/**
 * 
 */
package com.apanal.qlife.property.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.apanal.qlife.common.annotation.CurrentUser;
import com.apanal.qlife.common.constants.Constants;
import com.apanal.qlife.common.exception.BusinessException;
import com.apanal.qlife.common.page.Page;
import com.apanal.qlife.common.page.PageReturn;
import com.apanal.qlife.common.util.FileOperateUtil;
import com.apanal.qlife.property.model.Community;
import com.apanal.qlife.property.service.CommunityService;
import com.apanal.qlife.sys.model.User;

/**
 * @author Admin
 * 
 */
@Controller
@RequestMapping("/community")
public class CommunityController {

	private static final Logger logger = Logger.getLogger(CommunityController.class);

	@Autowired
	private CommunityService communityService;

	/**
	 * 查询社区列表
	 * 
	 * @param model
	 * @param community
	 * @return
	 */
	@RequestMapping("findCommunityList")
	public String findCommunityList(Community community, Page page, Model model) {
		PageReturn<Community> result = communityService.findCommunityList(community, page);
		model.addAttribute("result", result);
		return "property/communityList";
	}

	/**
	 * 跳转到新增社区页面
	 * 
	 * @param model
	 * @param community
	 * @return
	 */
	@RequestMapping("addCommunity")
	public String addCommunity(Model model, Community community) {
		return "property/addCommunity";
	}

	/**
	 * 查询单条社区
	 * 
	 * @param model
	 * @param community
	 * @return
	 */
	@RequestMapping("findCommunity")
	public String findCommunity(Model model, Community community) {
		model.addAttribute("com", communityService.findCommunity(community));
		return "property/editCommunity";
	}

	/**
	 * 查询单条社区
	 * 
	 * @param model
	 * @param community
	 * @return
	 */
	@RequestMapping("findCommunityDetails")
	public String findCommunityDetails(Model model, Community community) {
		model.addAttribute("com", communityService.findCommunity(community));
		return "property/communityDetails";
	}

	/**
	 * 新增社区
	 * 
	 * @param model
	 * @param community
	 * @return
	 */
	@ResponseBody
	@RequestMapping("saveCommunity")
	public String saveCommunity(Model model, Community community) {
		communityService.saveCommunity(community);
		return "";
	}

	/**
	 * 修改社区
	 * 
	 * @param model
	 * @param community
	 * @return
	 */
	@ResponseBody
	@RequestMapping("updateCommunity")
	public String updateCommunity(Model model, Community community) {
		communityService.updateCommunity(community);
		return "";
	}

	/**
	 * 查询物业信息
	 * 
	 * @param model
	 * @param community
	 * @return
	 */
	@RequestMapping("findOrgList")
	public String findOrgList(Model model) {
		return "property/tenementList";
	}

	/**
	 * 启用禁用
	 * 
	 * @param model
	 * @param community
	 * @return
	 */
	@ResponseBody
	@RequestMapping("updateCommunityNormal")
	public String updateCommunityNormal(Model model, Community community) {
		communityService.updateCommunityNormal(community);
		return "";
	}

	/**
	 * 分页查询,json返回
	 * 
	 * @param Area
	 * @param page
	 * @param model
	 * @return
	 */
	// @RequiresPermissions("user:view")
	@ResponseBody
	@RequestMapping(value = "listJson", method = RequestMethod.GET)
	public PageReturn<Community> listJson(Community community, Page page, Model model) {

		return communityService.selectRelationForPage(community, page);
	}

	/**
	 * 根据id字符串查询
	 * 
	 * @param ids
	 *            逗号分隔
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/{ids}/selectByIds", method = RequestMethod.GET)
	public List<Community> selectByIds(@PathVariable("ids") String ids) {
		return communityService.selectByIds(ids);
	}

	@RequestMapping("test")
	public String test(Model model, Community community) {
		return "property/test1";
	}

	@RequestMapping("import")
	public String importExcel(Model model, Community community) {
		return "property/importExcel";
	}

	@RequestMapping("importExcel")
	public String importExcelCommunity(@RequestParam("myfiles") MultipartFile[] myfiles, @CurrentUser User user,
			HttpServletRequest request, HttpServletResponse response) throws BusinessException, IOException {
		String result = "";
		for (MultipartFile myfile : myfiles) {
			if (!myfile.isEmpty()) {
				Date date = new Date();
				result = communityService.importExcelCommunity(myfile.getInputStream(), user);
				if (result == null || "".equals(result)) {
					/*
					 * String realPath =
					 * request.getSession().getServletContext()
					 * .getRealPath("/upload");
					 */
					try {
						String realPath = Constants.FILE_UPLOAD_PATH + Constants.PATH_IMPORT_EXCEL
								+ FileOperateUtil.getUploadPathByDate(date);
						FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath,
								new SimpleDateFormat("yyyyMMddHHmmss").format(date) + myfile.getOriginalFilename()));
					} catch (Exception e) {
						logger.error("拷贝业主租客导入文件失败", e);
					}
					// result = "导入成功!";
					return "redirect:findCommunityList.do";// 导入模块地址改变了,需重定向不然刷新会重复导入
				}
			} else {
				throw new BusinessException("导社区文件未上传");
			}
		}
		request.setAttribute("result", result);
		return "property/importExcel";
	}

	@RequestMapping("/download")
	public void download(HttpServletRequest request, HttpServletResponse response) {
		String filepath = request.getSession().getServletContext().getRealPath("/") + Constants.TEMPLATE;
		File file = new File(filepath);
		InputStream inputStream = null;
		OutputStream outputStream = null;
		byte[] b = new byte[1024];
		int len = 0;
		try {
			inputStream = new FileInputStream(file);
			outputStream = response.getOutputStream();

			response.setContentType("application/force-download");
			String filename = file.getName();
			// filename = filename.substring(36, filename.length());
			response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
			response.setContentLength((int) file.length());

			while ((len = inputStream.read(b)) != -1) {
				outputStream.write(b, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
					inputStream = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
					outputStream = null;
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
